package com.wanfajie.smsdistribute.main.fragment.group

import android.app.AlertDialog
import android.content.Context
import android.content.Context.INPUT_METHOD_SERVICE
import android.content.DialogInterface
import android.content.Intent
import android.os.Handler
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import com.wanfajie.smsdistribute.R
import com.wanfajie.smsdistribute.common.adapter.EditableRecyclerAdapter
import com.wanfajie.smsdistribute.common.adapter.RecyclerViewHolder
import com.wanfajie.smsdistribute.db.bean.phone.PhoneGroup
import com.wanfajie.smsdistribute.db.repository.impl.GroupRepositoryImpl
import com.wanfajie.smsdistribute.ui.phone_group_content.PhoneGroupContentActivity
import com.wanfajie.smsdistribute.util.confirm
import com.wanfajie.smsdistribute.util.toast

class PhoneGroupRecyclerAdapter(private val ctx: Context, data: List<PhoneGroup>)
    : EditableRecyclerAdapter<PhoneGroup>(ctx, R.layout.list_item_phone_group,
        R.menu.popup_phone_group, data, R.id.group_name) {

    init {
        setOnItemClickListener { group ->
            openGroupPage(group)
        }
    }

    private val mHandler = Handler()

    private fun openGroupPage(group: PhoneGroup) {
        val intent = Intent(ctx, PhoneGroupContentActivity::class.java)
        intent.putExtra(PhoneGroupContentActivity.EXTRA_KEY, group.id)
        ctx.startActivity(intent)
    }

    override fun onRenderView(viewHolder: RecyclerViewHolder, item: PhoneGroup) {
        viewHolder.get<TextView>(R.id.group_name).text = item.groupName
        item.phoneNumbers?.let { it ->
            val count: String
            val digest: CharSequence

            if (it.size == 0) {
                count = ctx.getString(R.string.empty)
                digest = ""
            } else {
                count = ctx.getString(R.string.specific_item_count, it.size)

                val sb = StringBuilder().apply {
                    val ith = it.iteratorThrow()
                    var i = 0
                    while (ith.hasNext() && i < 5 && length <= 18) {
                        append(ith.next().name)
                        append(", ")
                        i++
                    }

                    deleteCharAt(length-2)
                    append(ctx.getString(R.string.etc))

                    ith.closeQuietly()
                }

                digest = sb
            }

            viewHolder.get<TextView>(R.id.group_item_count).text = count
            viewHolder.get<TextView>(R.id.group_items_digest).text = digest
        }
    }

    override fun onCreatePopupMenu(inflater: MenuInflater, menu: Menu, item: PhoneGroup) {
        super.onCreatePopupMenu(inflater, menu, item)
        menu.findItem(R.id.item_name)?.title = item.groupName
    }

    override fun onMenuItemClick(menuItem: MenuItem, item: PhoneGroup): Boolean {
        return when (menuItem.itemId) {
            R.id.delete -> {
                confirm(ctx, R.string.delete,
                        ctx.getString(R.string.confirm_delete_group, item.groupName),
                        R.string.delete
                ) { _, witch ->
                    if (witch != DialogInterface.BUTTON_POSITIVE) return@confirm

                    removeItem(item)
                    if (GroupRepositoryImpl.removeGroup(item)) {
                        toast(strId = R.string.successfully_deleted)
                    } else {
                        toast("出错了")
                    }
                }

                true
            }
            R.id.rename -> with(AlertDialog.Builder(ctx)) {
                val name = item.groupName

                val view = View.inflate(ctx, R.layout.alert_create_group, null)
                val edit = view.findViewById<EditText>(R.id.et_group_name)
                edit.setText(name)
                edit.selectAll()

                setTitle(R.string.rename)
                setView(view)
                setNegativeButton(R.string.cancel, null)
                setPositiveButton(R.string.ok) { dialog, _ ->

                    val newName = edit.text.toString()
                    if (newName.isEmpty() || newName.isBlank()) {
                        val msg = ctx.getString(
                                R.string.cannot_be_empty,
                                ctx.getString(R.string.group_name)
                        )
                        toast(msg)
                        return@setPositiveButton
                    }

                    item.groupName = newName
                    if (GroupRepositoryImpl.updateGroup(item)) {
                        notifyItemChanged(indexOf(item))
                        toast(strId = R.string.successfully_modified)
                    } else {
                        item.groupName = name
                        val msg = ctx.getString(R.string.modified_failure_already_exists, newName)
                        toast(msg)
                    }
                }

                show()

                mHandler.post {
                    val inputManager = ctx.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                    inputManager.showSoftInput(edit, 0)
                }

                true
            }
            R.id.open -> {
                openGroupPage(item)
                true
            }
            else -> super.onMenuItemClick(menuItem, item)
        }
    }
}
